<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="站点" prop="siteId">
        <el-select v-model="queryParams.siteId" placeholder="请选择站点" clearable @change="handleSiteChange" style="width: 150px;">
          <el-option
            v-for="site in siteList"
            :key="site.siteId"
            :label="site.siteName"
            :value="site.siteId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="绑定状态" prop="bindStatus">
        <el-select v-model="queryParams.bindStatus" placeholder="请选择绑定状态"  style="width: 150px;" clearable>
          <el-option label="已绑定" value="0" />
          <el-option label="未绑定" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态"  style="width: 150px;" clearable>
          <el-option label="正常" value="0" />
          <el-option label="停用" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['collect:bind:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Connection"
          @click="handleAutoBind"
          :disabled="!currentSiteId"
          v-hasPermi="['collect:bind:auto']"
        >自动绑定</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="RefreshLeft"
          @click="handleClearBind"
          :disabled="!currentSiteId"
          v-hasPermi="['collect:bind:clear']"
        >清除绑定</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['collect:bind:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="bindList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="绑定ID" align="center" prop="bindId" width="80" />
      <el-table-column label="站点名称" align="center" prop="siteId" width="120">
        <template #default="scope">
          {{ getSiteName(scope.row.siteId) }}
        </template>
      </el-table-column>
      <el-table-column label="远程类型ID" align="center" prop="remoteTypeId" width="100" />
      <el-table-column label="远程类型名称" align="center" prop="remoteTypeName" />
      <el-table-column label="本地栏目" align="center" prop="localTypeName">
        <template #default="scope">
          <el-tag v-if="scope.row.localTypeId" type="success">
            {{ scope.row.localTypeName }}
          </el-tag>
          <el-tag v-else type="danger">未绑定</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="资源类型" align="center" prop="resourceType">
        <template #default="scope">
          <el-tag v-if="scope.row.resourceType === '1'">影视</el-tag>
          <el-tag v-else-if="scope.row.resourceType === '2'" type="success">文章</el-tag>
          <el-tag v-else-if="scope.row.resourceType === '3'" type="warning">短视频</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="绑定状态" align="center" prop="bindStatus">
        <template #default="scope">
          <el-tag v-if="scope.row.bindStatus === '0'" type="success">已绑定</el-tag>
          <el-tag v-else type="danger">未绑定</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <el-switch
            v-model="scope.row.status"
            active-value="0"
            inactive-value="1"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180">
        <template #default="scope">
          <el-button
            size="small"
            type="primary"
            link
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['collect:bind:edit']"
          >绑定</el-button>
          <el-button
            size="small"
            type="primary"
            link
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['collect:bind:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改采集绑定对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="bindRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="站点" prop="siteId">
          <el-select v-model="form.siteId" placeholder="请选择站点" @change="handleFormSiteChange">
            <el-option
              v-for="site in siteList"
              :key="site.siteId"
              :label="site.siteName"
              :value="site.siteId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="远程类型ID" prop="remoteTypeId">
          <el-input v-model="form.remoteTypeId" placeholder="请输入远程类型ID" />
        </el-form-item>
        <el-form-item label="远程类型名" prop="remoteTypeName">
          <el-input v-model="form.remoteTypeName" placeholder="请输入远程类型名称" />
        </el-form-item>
        <el-form-item label="资源类型" prop="resourceType">
          <el-select v-model="form.resourceType" placeholder="请选择资源类型" @change="handleResourceTypeChange">
            <el-option label="影视" value="1" />
            <el-option label="文章" value="2" />
            <el-option label="短视频" value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="本地栏目" prop="localTypeId" v-if="form.resourceType === '1'">
          <el-tree-select
            v-model="form.localTypeId"
            :data="columnTreeData"
            :props="{ value: 'columnId', label: 'name', children: 'children' }"
            placeholder="请选择本地栏目"
            check-strictly
            :render-after-expand="false"
            style="width: 100%"
            @change="handleLocalColumnChange"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="CollectBind">
import { listBind, getBind, delBind, addBind, updateBind, getBindsBySiteId, autoBindTypes, clearBindings } from "@/api/collect/bind";
import { listSite } from "@/api/collect/site";
import { listColumn } from "@/api/basic/column";
import { handleTree } from "@/utils/ruoyi";

const { proxy } = getCurrentInstance();
const route = useRoute();

const bindList = ref([]);
const siteList = ref([]);
const columnList = ref([]);
const columnTreeData = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const currentSiteId = ref(null);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    siteId: null,
    bindStatus: null,
    status: null
  },
  rules: {
    siteId: [
      { required: true, message: "站点不能为空", trigger: "change" }
    ],
    remoteTypeId: [
      { required: true, message: "远程类型ID不能为空", trigger: "blur" }
    ],
    remoteTypeName: [
      { required: true, message: "远程类型名称不能为空", trigger: "blur" }
    ],
    resourceType: [
      { required: true, message: "资源类型不能为空", trigger: "change" }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询采集绑定列表 */
function getList() {
  loading.value = true;
  listBind(queryParams.value).then(response => {
    bindList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/** 查询站点列表 */
function getSiteList() {
  listSite({ pageSize: 100 }).then(response => {
    siteList.value = response.rows;
  });
}

/** 查询栏目列表并构建树形结构 */
function getColumnList() {
  listColumn({ status: '0' }).then(response => {
    columnList.value = response.rows || response.data || [];
    columnTreeData.value = handleTree(columnList.value, 'columnId', 'parentId');
  });
}

/** 获取站点名称 */
function getSiteName(siteId) {
  const site = siteList.value.find(s => s.siteId === siteId);
  return site ? site.siteName : '';
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    bindId: null,
    bindKey: null,
    siteId: null,
    siteFlag: null,
    remoteTypeId: null,
    remoteTypeName: null,
    localTypeId: null,
    localColumn: null,
    localTypeName: null,
    resourceType: "1",
    bindStatus: "0",
    status: "0",
    remark: null
  };
  proxy.resetForm("bindRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 站点选择变化 */
function handleSiteChange(siteId) {
  currentSiteId.value = siteId;
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.bindId);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  if (currentSiteId.value) {
    form.value.siteId = currentSiteId.value;
    handleFormSiteChange(currentSiteId.value);
  }
  open.value = true;
  title.value = "添加采集绑定";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const bindId = row.bindId || ids.value;
  getBind(bindId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改采集绑定";
  });
}

/** 表单站点选择变化 */
function handleFormSiteChange(siteId) {
  const site = siteList.value.find(s => s.siteId === siteId);
  if (site) {
    form.value.siteFlag = site.siteFlag;
  }
}

/** 资源类型变化 */
function handleResourceTypeChange(value) {
  // 清空本地类型选择
  form.value.localTypeId = null;
  form.value.localColumn = null;
  form.value.localTypeName = null;
}

/** 本地栏目变化 */
function handleLocalColumnChange(columnId) {
  // 从columnList中查找对应的column（扁平列表）
  const column = columnList.value.find(c => c.columnId === columnId);
  if (column) {
    form.value.localTypeId = column.columnId;
    form.value.localTypeName = column.name;
    form.value.localColumn = column.value;
    form.value.bindStatus = '0'; // 设为已绑定
  }
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["bindRef"].validate(valid => {
    if (valid) {
      // 生成绑定键
      form.value.bindKey = form.value.siteFlag + '_' + form.value.remoteTypeId;

      if (form.value.bindId != null) {
        updateBind(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addBind(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const bindIds = row.bindId || ids.value;
  proxy.$modal.confirm('是否确认删除采集绑定编号为"' + bindIds + '"的数据项？').then(function() {
    return delBind(bindIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 自动绑定 */
function handleAutoBind() {
  if (!currentSiteId.value) {
    proxy.$modal.msgWarning("请先选择一个站点");
    return;
  }
  proxy.$modal.confirm('是否确认从远程站点自动获取并绑定类型？').then(() => {
    return autoBindTypes(currentSiteId.value);
  }).then((response) => {
    proxy.$modal.msgSuccess("自动绑定成功，创建了 " + response.data + " 个绑定");
    getList();
  }).catch(() => {});
}

/** 清除绑定 */
function handleClearBind() {
  if (!currentSiteId.value) {
    proxy.$modal.msgWarning("请先选择一个站点");
    return;
  }
  proxy.$modal.confirm('是否确认清除该站点的所有绑定？此操作不可恢复！').then(() => {
    return clearBindings(currentSiteId.value);
  }).then((response) => {
    proxy.$modal.msgSuccess("清除成功，删除了 " + response.data + " 个绑定");
    getList();
  }).catch(() => {});
}

/** 状态修改 */
function handleStatusChange(row) {
  let text = row.status === "0" ? "启用" : "停用";
  proxy.$modal.confirm('确认要"' + text + '"该绑定吗？').then(function() {
    return updateBind(row);
  }).then(() => {
    proxy.$modal.msgSuccess(text + "成功");
  }).catch(function() {
    row.status = row.status === "0" ? "1" : "0";
  });
}

// 初始化
// 从URL参数获取站点ID
const siteId = route.query.siteId;
if (siteId) {
  queryParams.value.siteId = parseInt(siteId);
  currentSiteId.value = parseInt(siteId);
}

getList();
getSiteList();
getColumnList();
</script>
